#include <iostream>
using namespace std;
#include <unistd.h>
#include <fcntl.h>
#include <string>

void SetNoBlock(int fd)
{
    //1. 获取对应描述符的属性
    int f1 = fcntl(0,F_GETFL);  
    if(fd < 0)
    {
        cout << "fcnt error" << endl;
        return;
    }
    //2. 将fd属性中对应的标志位设置为非阻塞
    fcntl(fd,F_SETFL,f1 | O_NONBLOCK);
}

int main()
{
    string str = "please enter#\n";
    SetNoBlock(0);
    char buf[1024];
    while(true)
    {
        write(1,str.c_str(),str.size());
        int n = read(0,buf,sizeof(buf) - 1);
        if(n > 0)
        {
            buf[n] = 0;
            cout << buf << endl;
        }
        else if(n == 0)
        {
            cout << "read to end" << endl;
            break;
        }
        else
        {
            //#define	EAGAIN		11	/* Try again */
            //#define	EWOULDBLOCK	EAGAIN	/* Operation would block */
            if(errno == EAGAIN || errno == EWOULDBLOCK)
            {
                cout << "底层数据未就绪" << endl;
                sleep(1);
                continue;
            }
            else if(errno == EINTR)
            {
                cout << "被中断，重新来" << endl;
                sleep(1);
                continue;
            }
            else
            {
                cout << "read fail,errno = " << errno << endl;
            }
        }

    }
    return 0;
}